const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const StylelintPlugin = require('stylelint-webpack-plugin')
const FileManagerWebpackPlugin = require('filemanager-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const webpack = require('webpack')
const path = require('path')
const env = require('./package')
const time = new Date()
const version = `${
  time.getMonth() + 1
}.${time.getDate()}.${time.getHours()}.${time.getMinutes()}`

module.exports = {
  publicPath: './',
  //publicPath: '/', //history需要设置
  //outputDir: 'dist', //输出文件目录
  runtimeCompiler: true,
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      //生产环境
      config.plugins = [
        ...config.plugins,
        new BundleAnalyzerPlugin(),
        //build完成后制成压缩包
        new FileManagerWebpackPlugin({
          events: {
            onStart: {},
            onEnd: {
              archive: [
                {
                  source: './dist',
                  destination: './dist/web.zip',
                },
              ],
            },
          },
        }),
        //gzip压缩代码，需要服务器支持
        //new CompressionPlugin({
        //  filename: "[path].gz[query]",
        //  algorithm: "gzip",
        //  test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
        //  threshold: 10240,
        //  minRatio: 0.8,
        //  deleteOriginalAssets: true,
        //}),
      ]
    } else {
      //开发环境
    }
    config.entry = {
      //polyfill: '@babel/polyfill' /*兼容低版本浏览器*/,
      app: './src/common/main',
    }
    config.output.filename = `js/[name].[hash:8]-${version || env.version}.js`
    config.output.chunkFilename = `js/[name].[hash:8].chunk-${version || env.version}.js`
    config.plugins = [
      ...config.plugins,
      new StylelintPlugin({
        files: ['**/*.{vue,htm,html,less,scss,sass}'],
        fix: true,
      }),
      //过滤掉moment中多余的语言包
      new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(zh-cn)$/),
    ]
    config.optimization = {
      minimize: true,
      splitChunks: {
        chunks: 'all',
        minChunks: 1,
        cacheGroups: {
          element: {
            name: `element-ui`,
            test: /element-ui/,
            priority: 0,
          },
          echarts: {
            name: `echarts`,
            test: /echarts/,
            priority: 0,
          },
          antv_x6: {
            name: `antv_x6`,
            test: /antv_x6/,
            priority: 0,
          },
          antv_layout: {
            name: `antv_layout`,
            test: /antv_layout/,
            priority: 0,
          },
          vendors: {
            test: /node_modules/,
            priority: -10,
          },
          default: {
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
    }
  },
  chainWebpack: config => {
    //console.log(config.module.rules);
    config.module
      .rule('less')
      .oneOf('vue')
      .use('style-resource-loader')
      .loader('style-resources-loader')
      .options({
        patterns: [
          path.resolve(__dirname, 'src/common/utils/overall.less'),
          path.resolve(__dirname, 'src/common/utils/style.less'),
          path.resolve(__dirname, 'src/utils/style.less'),
          // path.resolve(__dirname, 'src/common/utils/styleVar.less'),
        ],
        injector: 'prepend',
      })
      .end()
    config.module
      .rule('images')
      .use('url-loader')
      .tap(options => ({
        limit: 5 * 1024,
        name: `[name]-${version || env.version}.[ext]`,
        esModule: false,
        outputPath: 'media',
      }))
      .end()
  },
  productionSourceMap: false,
  devServer: {
    open: false, //浏览器自动打开页面
    historyApiFallback: {
      index: '/index.html',
    },
    proxy: {
      '/': {
        target: 'http://172.38.110.226:30030',
        ws: true,
        changeOrigin: true,
        //pathRewrite: {
        //  '^/': '',
        //},
      },
    },
  },
}
